/**
 * Jaxson ajax
 *
 * Copyright Remedy Interactive, licensed under Apache version 2 license:
 *
 *  http://www.apache.org/licenses/LICENSE-2.0.html
 *
 * This notice must remain in all java source files.
 */

package org.jaxson.tag.json;


import java.io.IOException;
import java.io.Serializable;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jaxson.struts.encoder.EncodingException;
import org.jaxson.struts.encoder.JsonEncoder;

/**
 * Render a javascript variable from an object stored in 
 * the request or session.
 * 
 * @author Joe Maisel
 */
public class JsonRenderingTag extends TagSupport
{
	private static final Log lager = LogFactory.getLog(JsonRenderingTag.class);
	
	private String scope;
	private String name;
	private String var;

	/*
	 * @see javax.servlet.jsp.tagext.TagSupport#doEndTag()
	 */
	@Override
	public int doEndTag() throws JspException
	{
		JsonEncoder enc = new JsonEncoder();
		enc.setWriter( pageContext.getOut() );

		try
		{
			if( var != null )
			{
				pageContext.getOut().write( "\n\t\tvar " + var + "=" );
			}
			
			 Serializable bean = new Boolean(false);
			
			if( scope.equals("session") && pageContext.getSession().getAttribute( name ) != null )
				bean = (Serializable)pageContext.getSession().getAttribute( name );
			
			if( scope.equals("request") && pageContext.getRequest().getAttribute( name ) != null )
				bean = (Serializable)pageContext.getRequest().getAttribute( name );
			
			lager.info( "bean=" + bean + " " + name );
			lager.info( pageContext.getRequest().getAttribute(name) );
			
			enc.encode( bean );

			pageContext.getOut().write( ";//" + bean );
		}
		catch( EncodingException e )
		{
			e.printStackTrace();
		}
		catch( IOException e )
		{
			e.printStackTrace();
		}

		return super.doEndTag();
	}

	/**
	 * @return the var
	 */
	public String getVar()
	{
		return var;
	}

	/**
	 * @param var
	 *            the var to set
	 */
	public void setVar( String var )
	{
		this.var = var;
	}

	/**
	 * @return the scope
	 */
	public String getScope()
	{
		return scope;
	}

	/**
	 * @param scope
	 *            the scope to set
	 */
	public void setScope( String scope )
	{
		this.scope = scope;
	}

	/**
	 * @return the name
	 */
	public String getName()
	{
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName( String name )
	{
		this.name = name;
	}

	private static final long serialVersionUID = 4506816822718994575L;
}
